package org.farm.config;


import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.iot20180120.AsyncClient;
import com.aliyun.sdk.service.iot20180120.models.PubRequest;
import com.aliyun.sdk.service.iot20180120.models.PubResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.iot.model.v20180120.QueryDevicePropertyDataRequest;
import com.aliyuncs.iot.model.v20180120.QueryDevicePropertyDataResponse;
import darabonba.core.client.ClientOverrideConfiguration;
import org.farm.pojo.TempHumidityData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;


@Component
@Configuration
public class AliyunIotConfig {

    @Autowired
    private IotConfig iotConfig;

    private String deviceName = "Q-werts";
    private String productKey = "k23ywgGj6Bq";

    public AsyncClient createClient() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
               .accessKeyId(iotConfig.getAccessKey())
               .accessKeySecret(iotConfig.getAccessSecret())
               .build());

        return AsyncClient.builder()
               .region(iotConfig.getRegion())
               .credentialsProvider(provider)
               .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                               .setEndpointOverride(iotConfig.getEndpoint())
                )
               .build();
    }


    public PubResponse publishMessageLight(AsyncClient client,int status) throws ExecutionException, InterruptedException {
        long id = System.currentTimeMillis();
        String json = "{\"method\":\"thing.service.property.set\",\"id\":\""+id+"\",\"params\":{\"NightLightSwitch\":"+ status+ "},\"version\":\"1.0.0\"}";

        PubRequest pubRequest = PubRequest.builder()
               .iotInstanceId(iotConfig.getIotInstanceId())
               .productKey(productKey)
               .deviceName(deviceName)  //从数据库获取
               .topicFullName("/k23ywgGj6Bq/" + deviceName  + "/user/get")
               .messageContent(
                        Base64.getEncoder().encodeToString(
                                (json).getBytes(StandardCharsets.UTF_8)))
               .build();

        CompletableFuture<PubResponse> response = client.pub(pubRequest);

        return response.get();
    }

    public PubResponse publishMessageWater(AsyncClient client,int status) throws ExecutionException, InterruptedException {
        long id = System.currentTimeMillis();
        String json = "{\"method\":\"thing.service.property.set\",\"id\":\""+id+"\",\"params\":{\"Nc\":"+ status+ "},\"version\":\"1.0.0\"}";

        PubRequest pubRequest = PubRequest.builder()
                .iotInstanceId(iotConfig.getIotInstanceId())
                .productKey(productKey)
                .deviceName(deviceName)  //从数据库获取
                .topicFullName("/k23ywgGj6Bq/" + deviceName  + "/user/get")
                .messageContent(
                        Base64.getEncoder().encodeToString(
                                (json).getBytes(StandardCharsets.UTF_8)))
                .build();

        CompletableFuture<PubResponse> response = client.pub(pubRequest);

        return response.get();
    }

    public TempHumidityData getTemperatureAndHumidity() throws Exception {
        DefaultAcsClient client = iotConfig.initClient();

        QueryDevicePropertyDataRequest tempRequest = new QueryDevicePropertyDataRequest();
        tempRequest.setSysRegionId(iotConfig.getRegion());
        tempRequest.setIotInstanceId(iotConfig.getIotInstanceId());
        tempRequest.setProductKey(productKey);
        tempRequest.setDeviceName(deviceName);
        tempRequest.setIdentifier("CurrentTemperature");
        tempRequest.setStartTime(System.currentTimeMillis() - 60 * 60 * 1000L); // 最近1小时
        tempRequest.setEndTime(System.currentTimeMillis());
        tempRequest.setAsc(1);
        tempRequest.setPageSize(1);

        QueryDevicePropertyDataResponse tempResponse = client.getAcsResponse(tempRequest);
        Double temperature = Double.valueOf(tempResponse.getData().getList().get(0).getValue());

        QueryDevicePropertyDataRequest humidRequest = new QueryDevicePropertyDataRequest();
        humidRequest.setSysRegionId(iotConfig.getRegion());
        humidRequest.setIotInstanceId(iotConfig.getIotInstanceId());
        humidRequest.setProductKey(productKey);
        humidRequest.setDeviceName(deviceName);
        humidRequest.setIdentifier("RelativeHumidity");
        humidRequest.setStartTime(System.currentTimeMillis() - 60 * 60 * 1000L);
        humidRequest.setEndTime(System.currentTimeMillis());
        humidRequest.setAsc(1);
        humidRequest.setPageSize(1);

        QueryDevicePropertyDataResponse humidResponse = client.getAcsResponse(humidRequest);
        Double humidity = Double.valueOf(humidResponse.getData().getList().get(0).getValue());

        return new TempHumidityData(temperature, humidity);
    }



}